package com.lazy.app.ui.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextPaint;
import android.text.TextWatcher;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.core.view.ViewCompat;
import androidx.fragment.app.Fragment;

import com.google.android.material.button.MaterialButton;
import com.google.android.material.checkbox.MaterialCheckBox;
import com.google.android.material.shape.MaterialShapeDrawable;
import com.google.android.material.shape.RoundedCornerTreatment;
import com.google.android.material.shape.ShapeAppearanceModel;
import com.google.android.material.shape.ShapePath;
import com.google.android.material.shape.TriangleEdgeTreatment;
import com.google.android.material.textfield.TextInputLayout;
import com.google.android.material.textview.MaterialTextView;
import com.lazy.app.R;
import com.lazy.app.presenter.H5Presenter;
import com.lazy.app.ui.act.H5Activity;
import com.lazy.app.utils.ImageCodeUtil;
import com.zndroid.permission.PermissionX;
import com.zndroid.permission.Permissions;
import com.zndroid.utils.XUtils;
import com.zndroid.utils.impl.SpannableStringUtil;

public class RegisterGuideFragment extends Fragment {
    private static final String KEY_LAYOUT_RES_ID = "KEY_LAYOUT_RES_ID";

    private int layoutResId;

    public static RegisterGuideFragment newInstance(@LayoutRes int layoutResId, @NonNull Bundle args) {
        RegisterGuideFragment fragment = new RegisterGuideFragment();

        args.putInt(KEY_LAYOUT_RES_ID, layoutResId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle bundle) {
        super.onCreate(bundle);

        Bundle args = getArguments();
        if (args != null) {
            layoutResId = args.getInt(KEY_LAYOUT_RES_ID);
        }
    }

    @Override
    public View onCreateView(
            LayoutInflater layoutInflater, @Nullable ViewGroup viewGroup, @Nullable Bundle bundle) {
        return layoutInflater.inflate(layoutResId, viewGroup, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        update(view);
    }

    private void update(View view) {
        switch (layoutResId) {
            case RegisterFragment.TYPE_REG:
                layout1(view);
                break;
            case RegisterFragment.TYPE_HEAD:
                layout2(view);
                break;
            case RegisterFragment.TYPE_GENDER:
                layout3(view);
                break;
            case RegisterFragment.TYPE_INDIVIDUATION:
                layout4(view);
                break;
            default:
                break;
        }
    }

    private void layout1(View view) {
        String KEY_PH = "phone";

        MaterialButton tipBtn = view.findViewById(R.id.tipBtn);
        MaterialButton verifyBtn = view.findViewById(R.id.btn_verify_code);
        MaterialTextView changeTextView = view.findViewById(R.id.tv_change);
        TextInputLayout phoneInputLayout = view.findViewById(R.id.input_ph);
        TextInputLayout randomInputLayout = view.findViewById(R.id.input_random_code);
        MaterialCheckBox descriptionCheckBox = view.findViewById(R.id.cb_description);
        AppCompatImageView randomImageView = view.findViewById(R.id.iv_change_random_code);

        Bundle bundle = getArguments();
        // init
        {
            phoneInputLayout.getEditText().setText(bundle.getString(KEY_PH, ""));
        }

        //change num
        changeTextView.setOnClickListener(v -> phoneInputLayout.getEditText().setText(""));

        // phone
        PermissionX.with(this)
                .permission(Permissions.READ_PHONE_NUMBERS)
                .request((list, b) -> phoneInputLayout.setPlaceholderText(XUtils.create().patternUtil().hidePhoneNumber("17601494455")));

        // random code
        randomInputLayout.getEditText().addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!editable.toString().equalsIgnoreCase(ImageCodeUtil.getInstance().getCode())) {
                    randomInputLayout.setError("随机码不正确");
                } else {
                    randomInputLayout.setError("");
                }
            }
        });
        randomImageView.setImageBitmap(ImageCodeUtil.getInstance().createBitmap());
        randomImageView.setOnClickListener(v -> {
            randomImageView.setImageBitmap(ImageCodeUtil.getInstance().createBitmap());
        });

        // description
        SpannableStringUtil.with(descriptionCheckBox)
                .append("勾选代表你同意")
                .append("《用户协议》")
                .setClickSpan(new ClickableSpan() {
                    @Override
                    public void onClick(@NonNull View widget) {
                        Intent intent = new Intent(requireContext(), H5Activity.class);

                        intent.putExtra(H5Presenter.H5_KEY_TITLE, "用户协议");
                        intent.putExtra(H5Presenter.H5_KEY_URL, H5Presenter.H5_URL_OF_USER_AGREEMENT);
                        intent.putExtra(H5Presenter.H5_KEY_TYPE, H5Presenter.H5_TYPE_OF_USER_AGREEMENT);
                        intent.putExtra(H5Presenter.H5_KEY_USE_NATIVE_TITLE, true);

                        startActivity(intent);
                    }

                    @Override
                    public void updateDrawState(@NonNull TextPaint ds) {
                        ds.setColor(Color.argb(255, 87, 107, 149));
                        ds.setUnderlineText(true);
                    }
                })
                .append("和")
                .append("《隐私政策》")
                .setClickSpan(new ClickableSpan() {
                    @Override
                    public void onClick(@NonNull View widget) {
                        Intent intent = new Intent(requireContext(), H5Activity.class);

                        intent.putExtra(H5Presenter.H5_KEY_TITLE, "隐私保护政策");
                        intent.putExtra(H5Presenter.H5_KEY_URL, H5Presenter.H5_URL_OF_PRIVACY_POLICY);
                        intent.putExtra(H5Presenter.H5_KEY_TYPE, H5Presenter.H5_TYPE_OF_PRIVACY_POLICY);
                        intent.putExtra(H5Presenter.H5_KEY_USE_NATIVE_TITLE, true);

                        startActivity(intent);
                    }

                    @Override
                    public void updateDrawState(@NonNull TextPaint ds) {
                        ds.setColor(Color.argb(255, 87, 107, 149));
                        ds.setUnderlineText(true);
                    }
                })
                .append("相关条款")
                .create();
        descriptionCheckBox.setOnCheckedChangeListener((compoundButton, b) -> {
            if (compoundButton.isPressed()) {
                tipBtn.setVisibility(View.GONE);
            }
        });

        // get verify code
        verifyBtn.setOnClickListener(v -> {
            if (!descriptionCheckBox.isChecked()) {
                ShapeAppearanceModel model = ShapeAppearanceModel
                        .builder()
                        .setAllCorners(new RoundedCornerTreatment())
                        .setAllCornerSizes(20f)
                        .setTopEdge(new TriangleEdgeTreatment(20f, false){
                            @Override
                            public void getEdgePath(float length, float center, float interpolation, @NonNull ShapePath shapePath) {
                                super.getEdgePath(length, center/5, interpolation, shapePath);
                            }
                        })
                        .build();
                MaterialShapeDrawable drawable = new MaterialShapeDrawable(model);
                drawable.setShadowCompatibilityMode(MaterialShapeDrawable.SHADOW_COMPAT_MODE_NEVER);
                drawable.initializeElevationOverlay(requireContext());
                drawable.setPaintStyle(Paint.Style.STROKE);

                ViewCompat.setBackground(tipBtn, drawable);
                tipBtn.setVisibility(View.VISIBLE);

            } else {
                //goto get
                Log.i("hyhy", ImageCodeUtil.getInstance().getCode());

                bundle.putString(KEY_PH, phoneInputLayout.getEditText().getText().toString());
            }
        });
    }

    private void layout2(View view) {

    }

    private void layout3(View view) {

    }

    private void layout4(View view) {

    }
}
